const LogModel = require('../../model/Log');
const moment = require('moment')
const Order = require('../../model/Order')
const User = require('../../model/User')
const ProductSub = require('../../model/ProductSub')
const Voucher = require('../../model/Voucher')
const Reimburse = require('../../model/Reimburse')
const MemberCard = require('../../model/MemberCard')
const Member = require('../../model/Member')
const UserPoint = require('../../model/userPoint')
const PointHistory = require('../../model/PointHistory')
const Staff = require('../../model/Staff')
const AdminUser = require('../../model/AdminUser')
const request = require('request')

const wxPublicAccessToken = require('../../util/businessUtil/wxPublicAccessToken');
const MyVoucher = require('../../model/MyVoucher');
const { Store } = require('express-session');

module.exports = {

    //获取日志列表
    getOneOrder: async (req, res, next) => {
        try {
            let data = await Order.findOne({ _id: req.body.id, isDelete: 0 }).populate({
                path: 'products.product',
                model: ProductSub,
                populate: { path: 'product' }
            }).populate({
                path: 'products.voucher',
                model: Voucher
            }).populate({
                path: 'reimburse',
                model: Reimburse
            }).populate('address coupon').exec()
            return res.ok('获取成功', data)
        } catch (e) {
            next(e)
        }
    },

    getOrderList: async (req, res, next) => {
        try {
            let option = {}
            option.isDelete = 0
            option.type = 0
            if (req.body.id) {
                option._id = req.body.id
            }
            if (req.body.cellphone) {
                let user = await User.find({ cellphone: new RegExp(req.body.cellphone, 'i') }, 'openid').exec()
                let openid = user.map(value => {
                    return value.openid
                })
                option.openid = openid
            }
            if (req.body.name) {
                let user = await User.find({ nickName: new RegExp(req.body.name, 'i') }, 'openid').exec()
                let openid = user.map(value => {
                    return value.openid
                })
                option.openid = openid
            }
            if (req.body.cellphone) {
                let user = await User.find({ cellphone: new RegExp(req.body.cellphone, 'i') }, 'openid').exec()
                let openid = user.map(value => {
                    return value.openid
                })
                option.openid = openid
            }
            if (req.body.type) {
                option.type = req.body.type
            }
            if (req.body.status) {
                option.status = req.body.status
            }
            if(req.body.userId){
                let user = await User.find({ _id:req.body.userId}, 'openid').exec()
                option.openid = user.openid
            }
            let sort = req.body.sort || -1
            let count = await Order.countDocuments(option).exec()
            let page = req.body.page || 1
            let pageSize = req.body.pageSize || count
            let data = await Order.find(option).skip((page - 1) * pageSize).limit(pageSize).sort({ createdAt: sort }).populate('user', 'cellphone').populate({
                path: 'products.product',
                model: ProductSub,
                populate: { path: 'product' }
            }).populate({
                path: 'products.voucher',
                model: Voucher
            }).populate({
                path: 'reimburse',
                model: Reimburse
            }).exec()
            let tempData = []
            data.forEach(async e => {
                let temp = JSON.parse(JSON.stringify(e))
                temp.cellphone = e.user.cellphone
                tempData.push(temp)
            })
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = tempData
            result.pageSize = pageSize
            return res.ok('获取列表成功', result)
        } catch (e) {
            let check = String(e).indexOf('Cast to ObjectId failed for value')
            if(check != -1){
                return res.send({code:201,msg:"无效的订单号"})
            }
            next(e)
        }
    },


    getVoucherOrderList: async (req, res, next) => {
        try {
            let option = {}
            option.isDelete = 0
            option.type = 1
            if (req.body.id) {
                option._id = req.body.id
            }
            if (req.body.name) {
                let user = await User.find({ nickName: new RegExp(req.body.name, 'i') }, 'openid').exec()
                let openid = user.map(value => {
                    return value.openid
                })
                option.openid = openid
            }
            if (req.body.cellphone) {
                let user = await User.find({ cellphone: new RegExp(req.body.cellphone, 'i') }, 'openid').exec()
                let openid = user.map(value => {
                    return value.openid
                })
                option.openid = openid
            }
            if (req.body.type) {
                option.type = req.body.type
            }
            if (req.body.status) {
                option.status = req.body.status
            }
            if(req.body.userId){
                let user = await User.find({ _id:req.body.userId}, 'openid').exec()
                option.openid = user.openid
            }
            if(req.body.storeId){
                // let voucherList = (await Voucher.find({store:{$in:[req.body.storeId]},isDelete:0},"_id").exec()).map(e=> { return String(e._id)})
                // let orderList = (await MyVoucher.find({voucher:{$in:voucherList},isDelete:0},"order").exec()).map(e=>{return String(e.order)})
                // option._id = {$in:orderList}
                let staffList = (await Staff.find({store:{$in:[req.body.storeId]},isDelete:0},"_id").exec()).map(e=> { return String(e._id)})
                option.staff = {$in:staffList}
            }
            let sort = req.body.sort || -1
            let count = await Order.countDocuments(option).exec()
            let page = req.body.page || 1
            let pageSize = req.body.pageSize || count


            let data = await Order.find(option).skip((page - 1) * pageSize).limit(pageSize).sort({ createdAt: sort }).populate('userVoucher user').populate({
                path: 'products.product',
                model: ProductSub,
                populate: { path: 'product' }
            }).populate({
                path: 'products.voucher',
                model: Voucher
            }).populate({
                path: 'reimburse',
                model: Reimburse
            }).populate({
                path: 'staff',
                model: Staff,
                populate: { path: 'store' }
            }).populate({
                path: 'account',
                model: AdminUser,
                populate: { path: 'store' }
            }).exec()
            let tempData = []
            data.forEach(async e => {
                let temp = JSON.parse(JSON.stringify(e))
                temp.cellphone = e.user.cellphone
                temp.userVoucher = e.userVoucher[0]
                tempData.push(temp)
            })
            // data.forEach(e => {
            //     e.userVoucher = e.userVoucher[0]
            // });


            // let data = await Order.aggregate([
            //     {
            //         $match: option
            //     },
            //     {
            //         $sort: {
            //             createdAt: sort
            //         }
            //     },
            //     {
            //         $skip: ((page - 1) * pageSize)
            //     },
            //     {
            //         $limit: pageSize
            //     },
            //     {
            //         $lookup: {
            //             from: "myVoucher",
            //             localField: '_id',
            //             foreignField: 'order',
            //             as: 'userVoucher'
            //         }
            //     },
            // ]).exec()
            // data.forEach(e => {
                // e.userVoucher = e.userVoucher[0]
            // });


            // let data = await Order.find(option).skip((page - 1) * pageSize).limit(pageSize).sort({ createdAt: sort }).populate({
            //     path: 'products.product',
            //     model: ProductSub,
            //     populate: { path: 'product' }
            // }).populate({
            //     path: 'products.voucher',
            //     model: Voucher
            // }).populate({
            //     path: 'reimburse',
            //     model: Reimburse
            // }).exec()
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = tempData
            result.pageSize = pageSize
            return res.ok('获取列表成功', result)
        } catch (e) {
            let check = String(e).indexOf('Cast to ObjectId failed for value')
            if(check != -1){
                return res.send({code:201,msg:"无效的订单号"})
            }
            next(e)
        }
    },

    changeOrder: async (req, res, next) => {
        try {
            let order = await Order.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            if (req.body.comment) {
                order.comment = req.body.comment
            }
            if (req.body.memo) {
                order.memo = req.body.memo
            }
            await order.save()
            return res.ok('修改成功', order)
        } catch (e) {
            next(e)
        }
    },


    addLogisticsStatus: async (req, res, next) => {
        try {
            let order = await Order.findOne({ _id: req.body.order, isDelete: 0 }).exec()
            if (req.body.logisticsCompany) {
                order.logisticsCompany = req.body.logisticsCompany
            }
            if (req.body.shipmentNumber) {
                order.shipmentNumber = req.body.shipmentNumber
            }
            order.shipDate = new Date()
            order.updatedAt = new Date()
            order.status = 4
            await order.save()
            return res.ok('修改成功', order)
        } catch (e) {
            next(e)
        }
    },

    cancelOrder: async (req, res, next) => {
        try {
            cancelOrderProcess(req, res)
        } catch (e) {
            next(e)
        }
    },


};


async function cancelOrderProcess(req, res) {
    let order = await Order.findOne({ _id: req.body.order, isDelete: 0 }).exec()
    let memberCardNumber = (await MemberCard.findOne({ isDelete: 0 }).exec()).cardId
    let member = await Member.findOne({ openid: order.openid, isDelete: 0 }).exec()
    let userPoint = await UserPoint.findOne({ openid: order.openid, isDelete: 0 }).exec()
    if(order.status == 5){
        return res.send({code:201,msg:"该订单已被撤销"})
    }
    order.updatedAt = new Date()
    order.cancelDate = new Date()
    order.status = 5
    await order.save()

    let myVoucher = await MyVoucher.find({order:order._id,isDelete:0}).exec()
    
    myVoucher.forEach(async(e) => {
        e.status =2
        e.isDelete = 1
        e.updatedAt = new Date()
        await e.save()
    });
    if (order.usePoint == 1) {
        let newPointHistory = new PointHistory({
            openid: order.openid,
            unionID: order.unionID,
            order: order._id,
            expenseDate: new Date(),
            manual: 0, // 1位人工，0为自动
            amount: order.amountOfUsePoint, // 变动的积分数量
            type: 0, // 0 为加，1为减
            isDelete: 0,
        })
        await newPointHistory.save()
        member.point = member.point + order.amountOfUsePoint
        member.updatedAt = new Date()
        await member.save()
        userPoint.current = userPoint.current + order.amountOfUsePoint
        userPoint.updatedAt = new Date()
        await userPoint.save()
        await order.save()
        wxPublicAccessToken.getAccessToken(function (token) {
            request({
                url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
                method: "POST",
                timeout: 10000,
                encoding: null,
                json: {
                    "code": member.code,
                    "card_id": memberCardNumber,
                    "bonus": member.point
                }
            }, function (error, response, body) {
                console.log(error)
                res.ok('撤销成功',order)
            })
        })
    }
    // return res.ok('撤销成功', order)
}